import {musicToAudit, musicToAuditList} from "@/utils/dataUtil";


const useMusicStore = defineStore('music-store',{
  state:()=>({
    musicAudio:[],
    musicPlayer:null,
    songListId: null
  }),
  getters:{
    getAudioIds(){
      const audios = [];
      if (this.musicAudio.length > 0){
        this.musicAudio.forEach(a=>{
          audios.push(a.id)
        })
      }
      return audios
    }
  },
  actions:{
    playSongList(songList,music,index){
      if (songList.id === this.songListId){
        if (music){
          // 当前播放列表为选中歌单，切换歌曲
          let number = this.getAudioIds.indexOf(music.id);
          this.musicPlayer =this.musicAudio[number];
        }else {
          this.musicPlayer =this.musicAudio[index];
        }
      } else {
        this.songListId = songList.id;
        let musicList = songList.musicList;
        let auditList = musicToAuditList(musicList);
        this.musicAudio = auditList;
        this.musicPlayer = auditList[index];
      }
    },
    addPlayList(music){
      if (this.musicAudio && this.musicAudio.length > 0){
        // 当前有播放
        let number = this.getAudioIds.indexOf(music.id);
        // 判断播放列表中是否存在
        if (number > -1){
          // 存在
        } else {
          this.musicAudio.push(musicToAudit(music))
        }
      }else {
        this.musicAudio.push(musicToAudit(music))
        this.musicPlayer = this.musicAudio[0];
      }
    },
    playMusic(music){
      // 播放歌曲
      if (this.musicAudio && this.musicAudio.length > 0){
        // 当前有播放
        let number = this.getAudioIds.indexOf(music.id);
        // 判断播放列表中是否存在
        if (number > -1){
          // 存在，切换播放
          this.musicPlayer = this.musicAudio[number]
        } else {
          this.musicAudio.push(musicToAudit(music))
          this.musicPlayer = this.musicAudio[this.musicAudio.length-1]
        }
      }else {
        this.musicAudio.push(musicToAudit(music))
        this.musicPlayer = this.musicAudio[this.musicAudio.length-1]
      }
    },
    playMusicList(list){
      // 播放列表
      if (list && list.length > 0){
        let auditList = musicToAuditList(list);
        this.musicAudio = auditList;
        this.musicPlayer = auditList[0];
      }
    }
  }
})
export default useMusicStore;
